package com.way.config;

import com.way.enums.DBTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DBContextHolder {

    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();

    private static final AtomicInteger count = new AtomicInteger(-1);

    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }

    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        log.info("--------------切换数据源到master--------------");
    }

    public static void slave() {
        if(count.get() > 9999) {
            count.set(-1);
        }
        int index = count.getAndIncrement() % 2;
        if(index == 0) {
            set(DBTypeEnum.SLAVE1);
            log.info("--------------切换数据源到slave1--------------");
        } else {
            set(DBTypeEnum.SLAVE2);
            log.info("--------------切换数据源到slave2--------------");
        }
    }
}
